from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse, get_object_or_404
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, ListView, UpdateView, DeleteView, DetailView
from django.utils import timezone

from main.models import Question
# from main.models import Book
from .forms import *
from .models import CustomUser
from django.contrib.auth.views import auth_login, auth_logout
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site

from utils.encrypt_decrypt import encrypt_data, decrypt_data
from django.core.signing import TimestampSigner, BadSignature, SignatureExpired

from django.conf import settings
from django.urls import reverse_lazy

from operate.models import Collect


@login_required
def change_head(request):
    if request.method == 'POST':
        cuif = UserInfoChangeForm(data=request.POST, files=request.FILES)
        if cuif.is_valid():
            request.user.head = cuif.cleaned_data['head']
            request.user.save()
            return redirect(reverse('user:center'))

        else:
            cuif = UserInfoChangeForm()
            return render(request, 'user/change_head.html', {'form': cuif})
    else:
        cuif = UserInfoChangeForm()
        return render(request, 'user/change_head.html', {'form': cuif})



@login_required
def change_name(request):
    if request.method == 'POST':
        cname = UsernameChangeForm(data=request.POST, instance=request.user)
        if cname.is_valid():

            cname.save()
            return redirect(reverse('user:center'))

        else:
            cname = UsernameChangeForm()
            return render(request, 'user/change_name.html', {'form': cname})
    else:
        cname = UsernameChangeForm()
        return render(request, 'user/change_name.html', {'form': cname})






@login_required
def center(request):
    # 获取用户提问过的问题列表
    questions = Question.objects.filter(author=request.user).order_by('-created_at')
    return render(request, 'user/center.html', {'questions': questions})

@login_required
def delete_question(request, question_id):
    # 获取问题对象
    question = get_object_or_404(Question, id=question_id)
    # 验证问题是否属于当前用户
    if question.author == request.user:
        question.delete()
    # 重定向回个人中心页面
    return redirect('user:center')


@login_required
def change_password(request):
    if request.method == 'POST':
        cgf = UserPassWordChangeForm(request.POST)
        if cgf.is_valid():
            if request.user.check_password(cgf.cleaned_data['old_password']):
                request.user.set_password(cgf.cleaned_data['password'])
                request.user.save()

                # 修改密码从新登录
                auth_logout(request)
                return redirect(reverse('user:login'))


            else:
                cgf.add_error("old_password", "原始密码不正确")
                return render(request, 'user/change_password.html', {"form": cgf})
        else:
            return render(request, 'user/change_password.html', {"form": cgf})
    else:
        cgf = UserPassWordChangeForm()
        return render(request, 'user/change_password.html', {"form": cgf})

def register(request):


    if request.method == "POST":

        rf = UserRegisterForm(request.POST)
        if rf.is_valid():
            user = rf.save(commit=False)
            user.is_active = False
            user.username = user.email
            user.set_password(rf.cleaned_data['password'])

            human = True

            user.save()



            # 加密用户id
            sign_util = TimestampSigner(key=settings.SECRET_KEY)

            encrypt_id = encrypt_data(f"{user.id}".encode())
            sign_id = sign_util.sign(encrypt_id)


            active_url = f"{get_current_site(request).domain}{reverse('user:active', args=(sign_id, ))}"
            active_html = f"<a href='http://{active_url}'>来自问答社区，点我激活</a>"

            # 向注册邮箱发送激活邮件
            user.email_user("激活账户", message="", html_message=active_html)

            return redirect(reverse('user:login'))
        else:
            return render(request, 'user/register.html', {"form": rf})
    else:

        rf = UserRegisterForm()
        return render(request, 'user/register.html', {"form": rf})

def logout(request):
    auth_logout(request)
    return redirect(reverse('user:login'))
def login(request):
    if request.method == "POST":
        lf = UserLoginForm(request.POST)
        if lf.is_valid():

            user = CustomUser.objects.filter(username=lf.cleaned_data['username']).first() or CustomUser.objects.filter(email=lf.cleaned_data['username']).first()
            if user:
                if user.check_password(lf.cleaned_data['password']):
                    if user.is_active:
                        auth_login(request, user)
                        next_url = request.GET.get('next')
                        if next_url:
                            return redirect(next_url)
                        else:
                            return redirect(reverse('main:home'))
                    else:
                        lf.add_error("username", "该用户尚未激活")
                        return render(request, 'user/login.html', {"form": lf})
                else:
                    lf.add_error("password", "密码错误")
                    return render(request, 'user/login.html', {"form": lf})
            else:
                lf.add_error("username", "用户名不存在")
                return render(request, 'user/login.html', {"form": lf})
        else:

            return render(request, 'user/login.html', {"form": lf})

    else:
        lf = UserLoginForm()
        return render(request, 'user/login.html', {"form": lf})



def active(request, id):
    try:
        sign_util = TimestampSigner(key=settings.SECRET_KEY)
        encrypted_id = sign_util.unsign(id, max_age=settings.ACTIVE_EMAIL_TIME)
        id = decrypt_data(encrypted_id)
        print(id, "----------")
        user = CustomUser.objects.filter(id=id).first()
        if user:
            user.is_active = True
            user.save()
            return redirect(reverse('user:login'))
        else:
            return HttpResponse("激活用户不存在")
    except SignatureExpired:
        return HttpResponse("超时, 下次及时激活")
    except BadSignature:
        return HttpResponse("激活链接错误")
    except Exception:
        return HttpResponse("未知错误")


@login_required
def my_collections(request):
    # 获取用户的收藏列表
    collections = Collect.objects.filter(user=request.user).order_by('-id')
    
    return render(request, 'user/my_collections.html', {'collections': collections})





